import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/account_detail.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/group/components/fake_dropdown_button.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 账户详情
class AccountDetailScreen extends StatefulWidget {
  static const routeName = '/AccountDetailScreen';
  final int args;

  const AccountDetailScreen({
    Key key,
    this.args,
  }) : super(key: key);

  @override
  _AccountDetailScreenState createState() => _AccountDetailScreenState();
}

class _AccountDetailScreenState extends State<AccountDetailScreen> {
  String _error;
  AccountDetail _accountDetail;
  List<ChangeLogItem> _list = [];
  RefreshController _refreshController;
  int _pageIndex;

  // 选择的时间查询参数项
  MapEntry<String, dynamic> _selectedTimeQuery;

  // 选择查询类目参数项
  MapEntry<String, dynamic> _selectedTotalItem;

  @override
  void initState() {
    super.initState();
    _onRefresh();
    _refreshController = RefreshController();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('账户详情'),
      ),
      body: _error == null && _accountDetail == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _accountDetail == null
              ? Center(
                  child: Text('$_error'),
                )
              : _buildBody(),
    );
  }

  SmartRefresher _buildBody() {
    return SmartRefresher(
      controller: _refreshController,
      enablePullUp: _accountDetail?.changeLogVos?.length == 10,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: SingleChildScrollView(
        padding: EdgeInsets.all(8.w),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: FakeDropdownButton(
                    text: _selectedTimeQuery?.value ??
                        _accountDetail.timeQueryItems.entries
                            .firstWhere(
                                (element) => element.key == _accountDetail.selectedTimeQuery)
                            .value,
                    onPressed: _showTimeQuerySheet,
                  ),
                ),
                SizedBox(
                  width: 8.w,
                ),
                Expanded(
                  child: FakeDropdownButton(
                    text: _selectedTotalItem?.value ??
                        _accountDetail.accountTotalItems.entries
                            .firstWhere(
                                (element) => element.key == _accountDetail.selectedTotalItem)
                            .value,
                    onPressed: _showTotalItemSheet,
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 8.w,
            ),
            _buildTotal(),
            SizedBox(
              height: 8.w,
            ),
            _buildLogs(),
          ],
        ),
      ),
    );
  }

  Widget _buildTotal() {
    if (_accountDetail.statisticsItems.isEmpty) {
      return Container();
    }
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
      ),
      child: Wrap(
        runSpacing: 8.w,
        children: List.generate(
          _accountDetail.statisticsItems.length,
          (index) => _buildTotalItem(_accountDetail.statisticsItems[index]),
        ),
      ),
    );
  }

  Widget _buildTotalItem(StatisticsItem data) {
    return Row(
      children: [
        Image.asset(
          'assets/icons/coin.png',
          width: 16.w,
          height: 16.w,
        ),
        SizedBox(
          width: 8.w,
        ),
        Expanded(
          child: Text('${data.itemName}'),
        ),
        SizedBox(
          width: 228.w,
          child: Row(
            children: [
              if (data.outcome != null)
                Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.green,
                      borderRadius: BorderRadius.circular(4.w),
                    ),
                    margin: EdgeInsets.only(left: 8.w),
                    child: Text(
                      '${data.outcome}',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              if (data.income != null)
                Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                      borderRadius: BorderRadius.circular(4.w),
                    ),
                    margin: EdgeInsets.only(left: 8.w),
                    child: Text(
                      '${data.income}',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                )
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildLogs() {
    return Wrap(
      runSpacing: 8.w,
      children: List.generate(
        _list.length,
        (index) => _buildLogItem(_list[index]),
      ),
    );
  }

  Widget _buildLogItem(ChangeLogItem data) {
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 4.w),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                ),
                child: Text(
                  '${data.id}',
                  style: TextStyle(color: Colors.grey, fontSize: 12.sp),
                ),
              ),
              SizedBox(
                width: 4.w,
              ),
              Expanded(
                child: Text(
                  '${data.accountTypeName}',
                  style: TextStyle(fontSize: 14.sp),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              SizedBox(
                width: 4.w,
              ),
              Expanded(
                child: Text(
                  '${data.operationTypeName}',
                  style: TextStyle(fontSize: 14.sp),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Text(
                '${data.amount}',
                style: TextStyle(
                  color: (double.tryParse(data.amount) ?? 0.0) < 0.0
                      ? Colors.green
                      : Theme.of(context).primaryColor,
                ),
              ),
              Text(' / '),
              Text('${data.balanceAfterChanged}'),
            ],
          ),
          SizedBox(
            height: 4.w,
          ),
          Text('${data.description}'),
          SizedBox(
            height: 4.w,
          ),
          Text('${data.changeTime}'),
        ],
      ),
    );
  }

  void _showTimeQuerySheet() async {
    final list = _accountDetail.timeQueryItems.entries.toList();
    final data = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemBuilder: (context, index) {
          final data = list[index];
          return ListTile(
            title: Text('${data.value}'),
            onTap: () => Navigator.of(context).pop(data),
          );
        },
        itemCount: list.length,
      ),
    );
    if (data == null) {
      return;
    }
    setState(() {
      _selectedTimeQuery = data;
    });
    _refreshController.requestRefresh();
  }

  void _showTotalItemSheet() async {
    final list = _accountDetail.accountTotalItems.entries.toList();
    final data = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => ListView.builder(
        shrinkWrap: true,
        itemBuilder: (context, index) {
          final data = list[index];
          return ListTile(
            title: Text('${data.value}'),
            onTap: () => Navigator.of(context).pop(data),
          );
        },
        itemCount: list.length,
      ),
    );
    if (data == null) {
      return;
    }
    setState(() {
      _selectedTotalItem = data;
    });
    _refreshController.requestRefresh();
  }

  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final accountDetail = await api.userAccountDetailTotal(
        widget.args,
        _pageIndex,
        _selectedTimeQuery?.key,
        _selectedTotalItem?.key,
      );
      if (!mounted) {
        return;
      }
      _refreshController.refreshCompleted();
      setState(() {
        _accountDetail = accountDetail;
        _list.clear();
        _list.addAll(accountDetail.changeLogVos);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
      _refreshController.refreshFailed();
    } catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = '$e';
      });
      _refreshController.refreshFailed();
    }
  }

  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final accountDetail = await api.userAccountDetailTotal(
        widget.args,
        _pageIndex,
        _selectedTimeQuery?.key,
        _selectedTotalItem?.key,
      );
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        // _accountDetail = accountDetail;
        _list.addAll(accountDetail.changeLogVos);
      });
    } catch (e) {
      _refreshController.loadFailed();
    }
  }
}
